<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>个股资金分析</title>
    <!-- 引入Tailwind CSS -->
    <!--    <script src="https://cdn.tailwindcss.com"></script>-->
    <!-- 引入Font Awesome -->
    <!--    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">-->

    <script src="/js/ll.js"></script>
    <link href="/css/font.css" rel="stylesheet">

    <!-- 配置Tailwind自定义颜色 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#1E40AF',
                        secondary: '#3B82F6',
                        success: '#10B981',
                        danger: '#EF4444',
                        neutral: '#64748B',
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>

    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .table-fixed-layout {
                table-layout: fixed;
            }
            .table-fixed-layout th,
            .table-fixed-layout td {
                border: 1px solid #ddd;  /* 细线边框 */
                padding: 8px;
            }

            .scrollbar-thin {
                scrollbar-width: thin;
            }
            .scrollbar-hide::-webkit-scrollbar {
                display: none;
            }
            .animate-fade-in {
                animation: fadeIn 0.5s ease-in-out;
            }
            .animate-slide-up {
                animation: slideUp 0.3s ease-out;
            }
            .sortable-header {
                cursor: pointer;
                position: relative;
                user-select: none;
            }
            .sortable-header:hover {
                background-color: rgba(0, 0, 0, 0.05);
            }
            .sort-indicator {
                margin-left: 5px;
                font-size: 0.8em;
                opacity: 0.7;
            }
            .filter-btn {
                @apply px-3 py-1.5 rounded-md text-sm transition-all duration-200;
            }
            .filter-btn.active {
                @apply bg-primary text-white;
            }
            .filter-btn:not(.active) {
                @apply bg-gray-100 text-gray-700 hover:bg-gray-200;
            }
        }

        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }

        @keyframes slideUp {
            from { transform: translateY(20px); opacity: 0; }
            to { transform: translateY(0); opacity: 1; }
        }
    </style>
</head>
<body class="bg-gray-50 font-sans text-gray-800 m-0 p-0">
<!-- 顶部导航栏 - 添加了sticky定位实现滚动置顶 -->
<header class="bg-primary text-white shadow-md w-full sticky top-0 z-50">
    <div class="flex justify-between items-center px-4 py-4">
        <div class="flex items-center space-x-2">
            <i class="fa fa-line-chart text-2xl" aria-hidden="true"></i>
            <h1 class="text-xl md:text-2xl font-bold">个股资金流向分析</h1>
            <h2 class="text-xl md:text-2xl font-bold " style="color: red">{大盘->板块->个股||主力->热度->分时}概念:前50,个股:前500</h2>
        </div>
        <div class="flex items-center space-x-4">
            <h1 class="text-xl md:text-2xl font-bold"><a href="/">首页</a></h1>
            <h1 class="text-xl md:text-2xl font-bold"><a href="/analysis">数据分析</a></h1>
            <h1 class="text-xl md:text-2xl font-bold"><a href="/limitup/search">涨停查询</a></h1>
            <h1 class="text-xl md:text-2xl font-bold"><a href="/gainian">概念资金</a></h1>
        </div>
    </div>
</header>

<!-- 主内容区 -->
<main class="w-full p-0 m-0 flex-grow flex flex-col min-h-[calc(100vh-64px)]">
    <!-- 筛选区域 - 定位在导航栏下方并保持置顶 -->
    <div class="bg-white rounded-lg shadow-sm p-4 animate-fade-in sticky top-[64px] z-40">
        <div class="flex flex-col md:flex-row justify-between items-start md:items-center">
            <div class="flex items-center gap-3 mt-3 md:mt-0 flex-wrap">
                <p class="text-lg text-gray-500" id="lastUpdateTime" style="color: red">最后更新: 加载中...</p>
                <button id="addOnlySelectStock" class="text-white flex items-center space-x-1 px-3 py-2 bg-secondary rounded-md hover:bg-green-700 transition-colors" onclick="addupdateFocusStocks('2')">
                    <span>自选</span>
                </button>
                <button id="delSelectStock" class="text-white flex items-center space-x-1 px-3 py-2 bg-green-600 rounded-md hover:bg-green-700 transition-colors" onclick="removeupdateFocusStock()">
                    <span>取消关注</span>
                </button>
                <button id="addSelectStock" class="text-white flex items-center space-x-1 px-3 py-2 bg-secondary rounded-md hover:bg-green-700 transition-colors" onclick="addupdateFocusStocks('1')">
                    <span>关注选择</span>
                </button>
                <button id="SelectStock" class="text-white flex items-center space-x-1 px-3 py-2 bg-green-600 rounded-md hover:bg-green-700 transition-colors" onclick="getSelectedStockCodesJQ()">
                    <span>复制选择</span>
                </button>
                <button id="refreshBtn" class="text-white flex items-center space-x-1 px-3 py-2 bg-secondary rounded-md hover:bg-green-700 transition-colors">
                    <i class="fa fa-refresh" aria-hidden="true"></i>
                    <span>刷新</span>
                </button>

                <div class="flex-1 min-w-[120px]">
                    <div class="flex gap-2">
                        <input type="date" id="startDate" class="w-40 px-3 py-2 border border-gray-100 rounded-md shadow-sm focus:outline-none focus:ring-primary focus:border-primary">
                    </div>
                </div>

                <button id="viewRisks" class="text-white flex items-center space-x-1 px-3 py-2 bg-secondary rounded-md hover:bg-green-700 transition-colors" onclick="openViewRisksStockCodesJQ()">
                    <span>查看风险</span>
                </button>
                <button id="getStock" class="text-white flex items-center space-x-1 px-3 py-2 bg-green-600 rounded-md hover:bg-green-700 transition-colors" onclick="openSelectedStockCodesJQ()">
                    <span>查看选择</span>
                </button>

                <!-- 新增：一键重置过滤条件按钮 -->
                <button class="text-white flex items-center space-x-1 px-3 py-2 bg-secondary rounded-md hover:bg-green-700 transition-colors" onclick="resetAllFilters()">
                    <i class="fa fa-refresh mr-1" aria-hidden="true"></i>重置过滤
                </button>

                <button id="saveFiltersBtn" class="px-3 py-2 bg-green-600 text-white rounded-md hover:bg-green-700 transition-colors flex items-center">
                    <i class="fa fa-save mr-1"></i> 保存条件
                </button>
                <div class="relative">
                    <select id="savedFiltersSelect" class="pl-3 pr-8 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary appearance-none bg-white cursor-pointer">
                        <option value="">加载保存的条件</option>
                        <!-- 动态填充保存的条件 -->
                    </select>
                    <i class="fa fa-chevron-down absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400 pointer-events-none" aria-hidden="true"></i>
                </div>
                <button id="deleteFilterBtn" class="px-2 py-2 text-gray-500 hover:text-red-600 transition-colors">
                    <i class="fa fa-trash"></i>
                </button>

            </div>
        </div>

        <div class="flex items-center gap-1 flex-nowrap overflow-x-auto pb-2">
            <div class="relative w-48">
                <input type="text" id="searchInput" placeholder="=关注-只关注+自选"
                       class="pl-6 pr-2 py-1 text-sm border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary">
            </div>
            <div class="relative w-48">
                <input type="text" id="searchGainianInput" placeholder="搜索概念...=为关注"
                       class="pl-6 pr-2 py-1 text-sm border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary">
            </div>

            <!-- 新增：市场板块过滤下拉框 -->
            <select class="filter-select w-24 border rounded px-2 py-1 text-sm focus:outline-none focus:ring-1 focus:ring-blue-500"
                    onchange="setMarketSegmentFilter(this.value)">
                <option value="all">市场板块</option>
                <option value="main">主板</option>
                <option value="growth">创业板</option>
                <option value="tech">科创板</option>
                <option value="st">ST股</option>
                <option value="north">北交所</option>
            </select>

            <!-- 策略选择下拉菜单 -->
            <select id="strategySelect"
                    class="filter-select w-28 border rounded px-2 py-1 text-sm focus:outline-none focus:ring-1 focus:ring-blue-500">
                <option value="">选择策略</option>
            </select>

            <!-- 1天主力过滤下拉框 -->
            <select class="filter-select w-36 border rounded px-2 py-1 text-sm focus:outline-none focus:ring-1 focus:ring-blue-500"
                    onchange="setMainCapitalFlow1dFilter(this.value)">
                <option value="mainAll" selected>1天主力</option>
                <option value="mainIn0">主出散进</option>
                <option value="mainIn00">主进散出</option>
                <option value="mainIn6">主进占6成</option>
                <option value="mainIn01">流入>0.01亿</option>
                <option value="mainIn05">流入>0.5亿</option>
                <option value="mainIn1">流入>1亿</option>
                <option value="mainIn5">流入>5亿</option>
                <option value="mainOut0">流出<1亿</option>
                <option value="mainOut1">流出>1亿</option>
                <option value="mainOut5">流出>5亿</option>
            </select>

            <!-- 市值过滤下拉框 -->
            <select class="filter-select w-28 border rounded px-2 py-1 text-sm focus:outline-none focus:ring-1 focus:ring-blue-500"
                    onchange="setMarketValueFilter(this.value)">
                <option value="marketAll" selected>市值</option>
                <option value="marketLt50"><50亿</option>
                <option value="marketLt100"><100亿</option>
                <option value="market100">100-500亿</option>
                <option value="market500">500-1000亿</option>
                <option value="market1000">>1000亿</option>
                <option value="market5000">>5000亿</option>
                <option value="market10000">>1万亿</option>
            </select>

            <!-- 获利过滤下拉框 -->
            <select class="filter-select w-28 border rounded px-2 py-1 text-sm focus:outline-none focus:ring-1 focus:ring-blue-500"
                    onchange="setProfitFilter(this.value)">
                <option value="profitAll" selected>获利</option>
                <option value="profitUp20">>20%</option>
                <option value="profitUp10">10-20%</option>
                <option value="profitUp5">5-10%</option>
                <option value="profitUp0">0-5%</option>
                <option value="profitUp00">>0%</option>
                <option value="profitDown0">亏0-5%</option>
                <option value="profitDown5">亏5-10%</option>
                <option value="profitDown10">亏>10%</option>
            </select>

            <!-- 15天有涨停下拉菜单 -->
            <select id="limitupSelect"
                    class="filter-select w-28 border rounded px-2 py-1 text-sm focus:outline-none focus:ring-1 focus:ring-blue-500">
                <option value="all">涨停</option>
                <option value="yes">15天有</option>
                <option value="no">15天无</option>
                <option value="today">今天涨停</option>
                <option value="todayF">今天首板</option>
                <option value="todayCont">今天连板</option>
                <option value="search">5天查询</option>
                <option value="review">15天复盘</option>
            </select>

            <!-- 涨幅过滤下拉框 -->
            <select class="filter-select w-28 border rounded px-2 py-1 text-sm focus:outline-none focus:ring-1 focus:ring-blue-500" onchange="setChangePercentFilter(this.value)">
                <option value="all" selected>涨幅</option>
                <option value="up5">涨>5%</option>
                <option value="up3">涨>3%</option>
                <option value="up0-3">涨0-3%</option>
                <option value="up1">涨>1%</option>
                <option value="up0">涨>0%</option>
                <option value="down1">跌>1%</option>
                <option value="down3">跌>3%</option>
                <option value="down5">跌>5%</option>
                <option value="limitUp">涨停</option>
                <option value="limitDown">跌停</option>
            </select>

            <!-- 换手率过滤下拉框 -->
            <select class="filter-select w-28 border rounded px-2 py-1 text-sm focus:outline-none focus:ring-1 focus:ring-blue-500"
                    onchange="setTurnoverRateFilter(this.value)">
                <option value="turnoverAll" selected>换手率</option>
                <option value="turnoverLt1"><1%</option>
                <option value="turnover1To3">1-3%</option>
                <option value="turnover3To5">3-5%</option>
                <option value="turnover5To10">5-10%</option>
                <option value="turnover10To20">10-20%</option>
                <option value="turnoverGt20">>20%</option>
            </select>

            <!-- 成交量过滤下拉框 -->
            <select class="filter-select w-28 border rounded px-2 py-1 text-sm focus:outline-none focus:ring-1 focus:ring-blue-500"
                    onchange="setVolumeFilter(this.value)">
                <option value="volumeAll" selected>成交量</option>
                <option value="volumeLt10"><10百万</option>
                <option value="volume10To50">10-50百万</option>
                <option value="volume50To100">50-100百万</option>
                <option value="volume100To500">100-500百万</option>
                <option value="volume500To1000">500-1000百万</option>
                <option value="volumeGt1000">>1000百万</option>
            </select>

            <!-- RSI过滤下拉框 -->
            <select class="filter-select w-18 border rounded px-2 py-1 text-sm focus:outline-none focus:ring-1 focus:ring-blue-500"
                    onchange="setRsiFilter(this.value)">
                <option value="rsiAll" selected>RSI</option>
                <option value="rsiLt30"><30(超卖)</option>
                <option value="rsi30To50">30-50</option>
                <option value="rsi50To70">50-70</option>
                <option value="rsiGt70">>70(超买)</option>
            </select>

            <!-- 趋势筛选下拉菜单 -->
            <select id="rankChangeSelect"
                    class="filter-select w-18 border rounded px-2 py-1 text-sm focus:outline-none focus:ring-1 focus:ring-blue-500">
                <option value="">趋势</option>
                <option value="5">上升>5</option>
                <option value="100">上升>100</option>
                <option value="200">上升>200</option>
                <option value="500">上升>500</option>
                <option value="-5">下降>5</option>
                <option value="-100">下降>100</option>
                <option value="-200">下降>200</option>
                <option value="-500">下降>500</option>
            </select>

            <!-- 新排名筛选下拉菜单 -->
            <select id="currentRankSelect" class="filter-select w-24 border rounded px-2 py-1 text-sm focus:outline-none focus:ring-1 focus:ring-blue-500">
                <option value="">新排名</option>
                <option value="100">前100</option>
                <option value="200">前200</option>
                <option value="500">前500</option>
                <option value="1000">前1000</option>
                <option value="2000">前2000</option>
            </select>
        </div>


        <!-- 新增：保存条件的模态框 -->
        <div id="saveFilterModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
            <div class="bg-white rounded-lg p-6 w-full max-w-md">
                <h3 class="text-lg font-semibold mb-4">保存当前过滤条件</h3>
                <div class="mb-4">
                    <label for="filterName" class="block text-sm font-medium text-gray-700 mb-1">条件名称</label>
                    <input type="text" id="filterName" class="w-full px-3 py-2 border border-gray-300 rounded-md" placeholder="例如：高涨幅筛选">
                </div>
                <div class="flex justify-end gap-2">
                    <button id="cancelSaveBtn" class="px-4 py-2 border border-gray-300 rounded-md hover:bg-gray-100 transition-colors">取消</button>
                    <button id="confirmSaveBtn" class="px-4 py-2 bg-primary text-white rounded-md hover:bg-primary/90 transition-colors">保存</button>
                </div>
            </div>
        </div>

        <style>
            .filter-select {
                cursor: pointer;
                background-color: white;
                transition: all 0.2s ease;
                font-weight: 500;
            }

            .filter-select:hover {
                border-color: #999;
            }
        </style>

        <div class="stats-container text-lg font-bold text-gray-700">
            总数: <span id="allCount" class="font-medium text-gray-900">-</span>
            &nbsp;&nbsp;&nbsp;上涨: <span id="upCount" class="font-medium text-red-500">-</span>
            &nbsp;&nbsp;&nbsp;下跌: <span id="downCount" class="font-medium text-green-500">-</span>
            &nbsp;&nbsp;&nbsp;平开: <span id="pinCount" class="font-medium text-gray-700">-</span>
            &nbsp;&nbsp;&nbsp;涨停: <span id="limitUpCount" class="font-medium text-red-600">-</span>
            &nbsp;&nbsp;&nbsp;跌停: <span id="limitDownCount" class="font-medium text-green-600">-</span>
            &nbsp;&nbsp;&nbsp;总资金: <span id="todayAll" class="font-medium text-red-600">-</span>
            &nbsp;总主力: <span id="todayAllMain" class="font-medium text-red-600">-</span>
            &nbsp;&nbsp;关注: <span id="flowGainian" class="font-medium text-red-600">-</span>
        </div>

    </div>


    <!-- 表格容器 -->
    <div class="bg-white shadow-sm overflow-hidden animate-slide-up flex-grow flex flex-col">
        <div class="overflow-x-auto scrollbar-thin flex-grow">
            <table class="w-full table-fixed-layout h-full">
                <thead class="bg-gray-100 text-left sticky top-0 z-10">
                <tr>
                    <th class="px-2 py-2 text-xs font-medium text-gray-500 w-16" style="width: 24px;">
                        <input type="checkbox" id="select-all" class="select-all">
                    </th>
                    <th data-sort="code" class="px-4 py-3 font-semibold text-gray-700 w-16 sortable-header">代码 <span class="sort-indicator"></span></th>
                    <th data-sort="name" class="px-5 py-4 font-semibold text-gray-700 w-24 sortable-header">名称 <span class="sort-indicator"></span></th>
                    <th data-sort="mainCapitalFlow1d" class="px-4 py-3 font-semibold text-gray-700 sortable-header">1主力 <span class="sort-indicator"></span></th>
                    <th data-sort="capitalFlow1d" class="px-4 py-3 font-semibold text-gray-700 sortable-header">1天总 <span class="sort-indicator"></span></th>
                    <th data-sort="mainCapitalFlow2d" class="px-4 py-3 font-semibold text-gray-700 sortable-header">2主力 <span class="sort-indicator"></span></th>
                    <th data-sort="capitalFlow2d" class="px-4 py-3 font-semibold text-gray-700 sortable-header">2天总 <span class="sort-indicator"></span></th>
                    <th data-sort="mainCapitalFlow3d" class="px-4 py-3 font-semibold text-gray-700 sortable-header">3主力 <span class="sort-indicator"></span></th>
                    <th data-sort="capitalFlow3d" class="px-4 py-3 font-semibold text-gray-700 sortable-header">3天总 <span class="sort-indicator"></span></th>
                    <th data-sort="mainCapitalFlow5d" class="px-4 py-3 font-semibold text-gray-700 sortable-header">5主力 <span class="sort-indicator"></span></th>
                    <th data-sort="capitalFlow5d" class="px-4 py-3 font-semibold text-gray-700 sortable-header">5天总 <span class="sort-indicator"></span></th>
                    <th data-sort="mainCapitalFlow6d" class="px-4 py-3 font-semibold text-gray-700 sortable-header">6主力 <span class="sort-indicator"></span></th>
                    <th data-sort="capitalFlow6d" class="px-4 py-3 font-semibold text-gray-700 sortable-header">6天总 <span class="sort-indicator"></span></th>
                    <th data-sort="mainCapitalFlow7d" class="px-4 py-3 font-semibold text-gray-700 sortable-header">7主力 <span class="sort-indicator"></span></th>
                    <th data-sort="capitalFlow7d" class="px-4 py-3 font-semibold text-gray-700 sortable-header">7天总 <span class="sort-indicator"></span></th>
                    <th data-sort="marketValue" class="px-4 py-3 font-semibold text-gray-700 sortable-header">市值 <span class="sort-indicator"></span></th>
                    <th data-sort="price" class="px-4 py-3 font-semibold text-gray-700 sortable-header">价格 <span class="sort-indicator"></span></th>
                    <th data-sort="mainCost" class="px-4 py-3 font-semibold text-gray-700 sortable-header">成本<span class="sort-indicator"></span></th>
                    <th data-sort="getmainCost" class="px-4 py-3 font-semibold text-gray-700 sortable-header">获利 <span class="sort-indicator"></span></th>
                    <th data-sort="changePercent" class="px-4 py-3 font-semibold text-gray-700 sortable-header">涨幅 <span class="sort-indicator"></span></th>
                    <th data-sort="volume" class="px-4 py-4 font-semibold text-gray-700 sortable-header" style="width: 70px;">量百万 <span class="sort-indicator"></span></th>
                    <th data-sort="turnoverRate" class="px-4 py-3 font-semibold text-gray-700 sortable-header">换手 <span class="sort-indicator"></span></th>
                    <th data-sort="rsi6" class="px-4 py-3 font-semibold text-gray-700 sortable-header">RSI <span class="sort-indicator"></span></th>
                    <th data-sort="concept" class="px-4 py-3 font-semibold text-gray-700 w-60 sortable-header">概念 <span class="sort-indicator"></span></th>
                    <th data-sort="currentRankPosition" class="px-2 py-1 font-semibold text-gray-700 w-14 sortable-header">新 <span class="sort-indicator"></span></th>
                    <th data-sort="currentOldRankPosition" class="px-2 py-1 font-semibold text-gray-700 w-14 sortable-header">旧 <span class="sort-indicator"></span></th>
                    <th data-sort="rankChange" class="px-2 py-1 font-semibold text-gray-700 w-20 sortable-header">趋势 <span class="sort-indicator"></span></th>
                </tr>
                </thead>
                <tbody id="stockTableBody">
                <!-- 表格内容将通过JavaScript动态填充 -->
                <tr>
                    <td colspan="27" class="px-4 py-8 text-center text-gray-500">
                        <div class="flex flex-col items-center">
                            <i class="fa fa-circle-o-notch fa-spin text-2xl mb-2" aria-hidden="true"></i>
                            <p>正在加载数据...</p>
                        </div>
                    </td>
                </tr>
                </tbody>
            </table>
        </div>

        <!-- 表格底部信息 -->
        <div class="px-4 py-3 bg-gray-50 border-t border-gray-200 flex justify-between items-center">
            <div class="text-sm text-gray-500">
                显示 <span id="shownCount">0</span> 条，共 <span id="totalCount">0</span> 条记录
            </div>
            <div class="flex space-x-2">
                <button id="prevPage" class="px-3 py-1 border border-gray-300 rounded-md text-sm bg-white hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed" disabled>
                    <i class="fa fa-chevron-left" aria-hidden="true"></i> 上一页
                </button>
                <button id="nextPage" class="px-3 py-1 border border-gray-300 rounded-md text-sm bg-white hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed" disabled>
                    下一页 <i class="fa fa-chevron-right" aria-hidden="true"></i>
                </button>
            </div>
        </div>
    </div>
</main>

<!-- 页脚 -->
<footer class="bg-gray-800 text-white py-6 w-full">
    <div class="container mx-auto px-4 text-center text-sm">
        <p>© 2025 股票资金流向统计分析系统 - 数据仅供参考</p>
    </div>
</footer>

<!-- JavaScript -->
<script src="/js/jquery.min.js"></script>
<script src="/js/bootstrap.bundle.min.js"></script>
<script>
    // 全局变量
    let stockData = [];
    let flowStock = "";
    let todaylimitstr = "";
    let todaylimitcontinuousstr = "";
    let limit10dstr = "";
    let searchtr = "";
    let notlimit10dstr = "";
    let review15dstr = "";
    let allOptional = "";
    let onlyFlowStock = "";
    let flowGainian = "";
    let todayAll = 0;
    let todayAllMain = 0;
    let createdAt = "";
    let filteredData = [];
    let currentPage = 1;
    const pageSize = 200;

    // 过滤条件变量
    let changePercentFilter = 'all'; // 涨幅过滤，默认为全部
    let mainCapitalFlow1dFilter = 'mainAll'; // 1天主力资金过滤，默认为全部
    let profitFilter = 'profitAll'; // 获利过滤，默认为全部
    let currentRankFilter = ''; // 新排名过滤，默认为全部
    let marketValueFilter = 'marketAll'; // 市值过滤，默认为全部
    let turnoverRateFilter = 'turnoverAll'; // 换手率过滤，默认为全部
    let volumeFilter = 'volumeAll'; // 成交量过滤条件
    let rsi6Filter = 'rsiAll'; // RSI过滤条件
    let marketSegmentFilter = 'all'; // 市场板块过滤条件，新增

    // 排序状态变量
    let currentSortField = 'currentRankPosition'; // 默认按最新排名排序
    let currentSortDirection = 'asc'; // 默认升序

    let limitupFilter = 'all'; // 涨停过滤条件，默认为全部


    $(document).ready(function() {
        // 为表格行绑定点击事件
        $('table').on('click', 'tr', function(e) {
            // 排除直接点击复选框的情况
            if($(e.target).is('input[type="checkbox"]')) return;

            // 获取当前行的复选框
            var $checkbox = $(this).find('.row-checkbox');

            // 切换选中状态
            $checkbox.prop('checked', !$checkbox.prop('checked'));

            // 可选：添加行高亮样式
            $(this).toggleClass('active', $checkbox.prop('checked'));
        });
    });


    // DOM加载完成后执行
    document.addEventListener('DOMContentLoaded', function() {
        const urlParams = new URLSearchParams(window.location.search);
        const code = urlParams.get('code');
        // 如果URL中有参数，设置到对应输入框
        if (code) {
            document.getElementById('searchInput').value = code;
            // 自动执行搜索
            setTimeout(() => {
                filterByAllConditions();
                currentPage = 1;
                renderTable();
            }, 500);
        }

        // 加载股票数据
        loadStockData();

        // 加载策略数据
        loadStrategyData();

        // 绑定事件监听器
        document.getElementById('refreshBtn').addEventListener('click', refreshData);
        document.getElementById('searchInput').addEventListener('input', handleSearch);
        document.getElementById('searchGainianInput').addEventListener('input', handleSearchGainian);
        // 趋势选择下拉框事件
        document.getElementById('rankChangeSelect').addEventListener('change', handleRankChange);
        // 新排名筛选下拉框事件
        document.getElementById('currentRankSelect').addEventListener('change', function() {
            currentRankFilter = this.value;
            filterByAllConditions();
            currentPage = 1;
            renderTable();
        });

        // 策略选择下拉框事件
        document.getElementById('strategySelect').addEventListener('change', function() {
            const selectedValue = this.value;
            // if (selectedValue) {
            // 将选中的值填充到搜索框
            document.getElementById('searchInput').value = selectedValue;
            // 执行查询
            handleSearch();
            // }
        });

        // 涨停情况选择下拉框事件
        document.getElementById('limitupSelect').addEventListener('change', function() {
            limitupFilter = this.value;
            filterByAllConditions();
            currentPage = 1;
            renderTable();
        });

        document.getElementById('prevPage').addEventListener('click', goToPrevPage);
        document.getElementById('nextPage').addEventListener('click', goToNextPage);
        document.getElementById('startDate').addEventListener('change', function() {
            // 日期变化时调用接口重新获取数据
            refreshData();
        });

        // 初始化表头点击排序功能
        initSortableHeaders();

        // 全选复选框事件
        document.getElementById('select-all').addEventListener('click', setupCheckboxHandler);
        // 设置默认日期为当天
        const today = new Date();
        document.getElementById('startDate').valueAsDate = today;

        // 初始化过滤条件相关功能
        initFilterSaveFunctionality();
    });

    // 初始化过滤条件保存功能
    function initFilterSaveFunctionality() {
        // 从服务器加载所有保存的过滤条件
        loadSavedFiltersFromServer();

        // 保存过滤条件按钮点击事件
        document.getElementById('saveFiltersBtn').addEventListener('click', function() {
            document.getElementById('saveFilterModal').classList.remove('hidden');
            document.getElementById('filterName').focus();
        });

        // 取消保存按钮点击事件
        document.getElementById('cancelSaveBtn').addEventListener('click', function() {
            document.getElementById('saveFilterModal').classList.add('hidden');
            document.getElementById('filterName').value = '';
        });

        // 确认保存按钮点击事件
        document.getElementById('confirmSaveBtn').addEventListener('click', saveCurrentFiltersToServer);

        // 加载保存的过滤条件
        document.getElementById('savedFiltersSelect').addEventListener('change', loadSelectedFilterFromServer);

        // 删除选中的过滤条件
        document.getElementById('deleteFilterBtn').addEventListener('click', deleteSelectedFilterFromServer);

    }

    // 获取当前所有过滤条件的值
    function getCurrentFilters() {
        const strategySelect = document.getElementById('strategySelect');
        const selectedStrategyText = strategySelect.options[strategySelect.selectedIndex].text;

        let searchInputText = document.getElementById('searchInput').value;
        if (selectedStrategyText != null) {
            searchInputText = '';
        }

        return {
            searchInput: searchInputText,
            searchGainianInput: document.getElementById('searchGainianInput').value,
            rankChangeSelect: document.getElementById('rankChangeSelect').value,
            currentRankSelect: document.getElementById('currentRankSelect').value,
            limitupSelect: document.getElementById('limitupSelect').value,
            changePercentFilter: document.querySelector('select[onchange="setChangePercentFilter(this.value)"]').value,
            marketValueFilter: document.querySelector('select[onchange="setMarketValueFilter(this.value)"]').value,
            mainCapitalFlow1dFilter: document.querySelector('select[onchange="setMainCapitalFlow1dFilter(this.value)"]').value,
            profitFilter: document.querySelector('select[onchange="setProfitFilter(this.value)"]').value,
            turnoverRateFilter: document.querySelector('select[onchange="setTurnoverRateFilter(this.value)"]').value,
            volumeFilter: document.querySelector('select[onchange="setVolumeFilter(this.value)"]').value,
            rsi6Filter: document.querySelector('select[onchange="setRsiFilter(this.value)"]').value,
            strategySelect: selectedStrategyText,
            marketSegmentFilter: document.querySelector('select[onchange="setMarketSegmentFilter(this.value)"]').value // 新增
        };
    }


    // 保存当前过滤条件到服务器
    function saveCurrentFiltersToServer() {
        const filterName = document.getElementById('filterName').value.trim();

        if (!filterName) {
            alert('请输入过滤条件名称');
            return;
        }

        // 获取当前过滤条件
        const filterData = getCurrentFilters();
        // 添加名称
        filterData.name = filterName;

        // 发送到服务器
        fetch('/api/filter-conditions', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(filterData)
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error('保存过滤条件失败');
                }
                return response.json();
            })
            .then(data => {
                if (data.success) {
                    // 刷新列表
                    loadSavedFiltersFromServer();
                    // 关闭模态框
                    document.getElementById('saveFilterModal').classList.add('hidden');
                    document.getElementById('filterName').value = '';
                    // 显示成功提示
                    showToast(`过滤条件"${filterName}"已保存`);
                } else {
                    throw new Error(data.message || '保存失败');
                }
            })
            .catch(error => {
                console.error('保存过滤条件失败:', error);
                showToast(`保存失败: ${error.message}`);
            });
    }

    // 从服务器加载选中的过滤条件
    function loadSelectedFilterFromServer() {
        const selectedId = this.value;
        if (!selectedId) return;

        // 调用API获取指定ID的过滤条件
        fetch(`/api/filter-conditions/${selectedId}`)
            .then(response => {
                if (!response.ok) {
                    throw new Error('获取过滤条件失败');
                }
                return response.json();
            })
            .then(filter => {
                if (!filter) {
                    throw new Error('未找到过滤条件');
                }

                // 应用过滤条件
                document.getElementById('searchInput').value = filter.searchInput || '';
                document.getElementById('searchGainianInput').value = filter.searchGainianInput || '';
                document.getElementById('rankChangeSelect').value = filter.rankChangeSelect || '';
                document.getElementById('currentRankSelect').value = filter.currentRankSelect || '';
                document.getElementById('limitupSelect').value = filter.limitupSelect || '';
                document.querySelector('select[onchange="setChangePercentFilter(this.value)"]').value = filter.changePercentFilter || 'all';
                document.querySelector('select[onchange="setMarketValueFilter(this.value)"]').value = filter.marketValueFilter || 'marketAll';
                document.querySelector('select[onchange="setMainCapitalFlow1dFilter(this.value)"]').value = filter.mainCapitalFlow1dFilter || 'mainAll';
                document.querySelector('select[onchange="setProfitFilter(this.value)"]').value = filter.profitFilter || 'profitAll';
                // 应用换手率过滤条件
                document.querySelector('select[onchange="setTurnoverRateFilter(this.value)"]').value = filter.turnoverRateFilter || 'turnoverAll';

                // 应用成交量过滤条件
                document.querySelector('select[onchange="setVolumeFilter(this.value)"]').value = filter.volumeFilter || 'volumeAll';
                // 应用RSI过滤条件
                document.querySelector('select[onchange="setRsiFilter(this.value)"]').value = filter.rsi6Filter || 'rsiAll';

                // 应用市场板块过滤条件（新增）
                document.querySelector('select[onchange="setMarketSegmentFilter(this.value)"]').value = filter.marketSegmentFilter || 'all';


                // 处理策略选择 - 根据保存的文本找到对应的选项
                const strategySelect = document.getElementById('strategySelect');
                const strategyText = filter.strategySelect || '';

                // 如果有保存的策略文本，尝试找到并选中对应的选项
                if (strategyText && strategyText !== '选择策略') {
                    for (let i = 0; i < strategySelect.options.length; i++) {
                        if (strategySelect.options[i].text === strategyText) {
                            strategySelect.selectedIndex = i;

                            const selectedValue = strategySelect.options[i].value;
                            // if (selectedValue) {
                            // 将选中的值填充到搜索框
                            document.getElementById('searchInput').value = selectedValue;
                            // 执行查询
                            handleSearch();
                            // }
                        }
                    }
                } else {
                    // 默认选中第一个选项
                    strategySelect.selectedIndex = 0;
                }

                // 更新全局过滤变量
                changePercentFilter = filter.changePercentFilter || 'all';
                mainCapitalFlow1dFilter = filter.mainCapitalFlow1dFilter || 'mainAll';
                profitFilter = filter.profitFilter || 'profitAll';
                currentRankFilter = filter.currentRankSelect || '';
                marketValueFilter = filter.marketValueFilter || 'marketAll';
                limitupFilter = filter.limitupSelect || 'all';
                turnoverRateFilter = filter.turnoverRateFilter || 'turnoverAll';
                volumeFilter = filter.volumeFilter || 'volumeAll';
                rsi6Filter = filter.rsi6Filter || 'rsiAll';
                marketSegmentFilter = filter.marketSegmentFilter || 'all'; // 新增

                // 触发过滤操作
                filterByAllConditions();
                currentPage = 1;
                renderTable();

                // 显示提示
                showToast(`已加载过滤条件: ${filter.name}`);
            })
            .catch(error => {
                console.error('加载过滤条件失败:', error);
                showToast(`加载失败: ${error.message}`);
            });
    }

    // 从服务器删除选中的过滤条件
    function deleteSelectedFilterFromServer() {
        const selectElement = document.getElementById('savedFiltersSelect');
        const selectedId = selectElement.value;

        if (!selectedId) {
            showToast('请先选择要删除的过滤条件');
            return;
        }

        // 获取选中的条件名称
        const selectedOption = selectElement.options[selectElement.selectedIndex];
        const filterName = selectedOption.textContent.split(' (')[0];

        if (confirm(`确定要删除过滤条件"${filterName}"吗？`)) {
            // 调用API删除
            fetch(`/api/filter-conditions/${selectedId}`, {
                method: 'DELETE'
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('删除过滤条件失败');
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.success) {
                        // 刷新列表
                        loadSavedFiltersFromServer();
                        // 重置选择框
                        selectElement.value = '';
                        showToast(`过滤条件"${filterName}"已删除`);
                    } else {
                        throw new Error(data.message || '删除失败');
                    }
                })
                .catch(error => {
                    console.error('删除过滤条件失败:', error);
                    showToast(`删除失败: ${error.message}`);
                });
        }
    }

    const formatTimeMD = (timeStr) => {
        if (!timeStr) return '-';
        const date = new Date(timeStr);
        // 月份从0开始，需要+1
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        // 格式化为 "月-日 时:分" 形式
        return `${month}-${day}`;
    };

    // 从服务器加载所有保存的过滤条件
    function loadSavedFiltersFromServer() {
        const selectElement = document.getElementById('savedFiltersSelect');

        // 清空现有选项（保留第一个提示选项）
        while (selectElement.options.length > 1) {
            selectElement.remove(1);
        }

        // 调用API获取过滤条件
        fetch('/api/filter-conditions')
            .then(response => {
                if (!response.ok) {
                    throw new Error('获取过滤条件失败');
                }
                return response.json();
            })
            .then(filters => {
                // 添加保存的条件到下拉框
                filters.forEach(filter => {
                    const option = document.createElement('option');
                    option.value = filter.id;
                    // 格式化日期显示
                    const formattedDate = formatTimeMD(filter.createdAt);
                    option.textContent = `${filter.name}(${formattedDate})`;
                    selectElement.appendChild(option);
                });
            })
            .catch(error => {
                console.error('加载过滤条件失败:', error);
                showToast('加载过滤条件失败');
            });
    }

    // 显示提示消息
    function showToast(message) {
        // 创建提示元素
        const toast = document.createElement('div');
        toast.className = 'fixed bottom-4 left-50 bg-gray-800 text-white px-4 py-2 rounded-md shadow-lg z-50';
        toast.textContent = message;
        document.body.appendChild(toast);

        // 10秒后自动移除
        setTimeout(() => {
            toast.classList.add('opacity-0', 'transition-opacity', 'duration-300');
            setTimeout(() => toast.remove(), 2000);
        }, 10000);
    }

    // 设置获利过滤条件
    function setProfitFilter(filterType) {
        // 更新过滤条件
        profitFilter = filterType;

        // 应用过滤并重置分页
        filterByAllConditions();
        currentPage = 1;
        renderTable();
    }

    // 设置市值过滤条件
    function setMarketValueFilter(filterType) {
        // 更新过滤条件
        marketValueFilter = filterType;

        // 应用过滤并重置分页
        filterByAllConditions();
        currentPage = 1;
        renderTable();
    }

    // 设置换手率过滤条件
    function setTurnoverRateFilter(filterType) {
        // 更新过滤条件
        turnoverRateFilter = filterType;

        // 应用过滤并重置分页
        filterByAllConditions();
        currentPage = 1;
        renderTable();
    }

    // 设置成交量过滤条件
    function setVolumeFilter(filterType) {
        // 更新过滤条件
        volumeFilter = filterType;

        // 应用过滤并重置分页
        filterByAllConditions();
        currentPage = 1;
        renderTable();
    }

    // 设置RSI过滤条件
    function setRsiFilter(filterType) {
        // 更新过滤条件
        rsi6Filter = filterType;

        // 应用过滤并重置分页
        filterByAllConditions();
        currentPage = 1;
        renderTable();
    }

    // 设置市场板块过滤条件（新增）
    function setMarketSegmentFilter(filterType) {
        // 更新过滤条件
        marketSegmentFilter = filterType;

        // 应用过滤并重置分页
        filterByAllConditions();
        currentPage = 1;
        renderTable();
    }

    // 重置所有过滤条件
    function resetAllFilters() {
        // 重置所有过滤条件变量
        changePercentFilter = 'all';
        mainCapitalFlow1dFilter = 'mainAll';
        profitFilter = 'profitAll';
        limitupFilter = 'all';
        currentRankFilter = ''; // 重置新排名过滤条件
        marketValueFilter = 'marketAll'; // 重置市值过滤条件
        turnoverRateFilter = 'turnoverAll'; // 重置换手率过滤条件
        volumeFilter = 'volumeAll'; // 重置成交量过滤条件
        rsi6Filter = 'rsiAll'; // 重置RSI过滤条件
        marketSegmentFilter = 'all'; // 重置市场板块过滤条件（新增）

        // 清空所有搜索输入框
        document.getElementById('searchInput').value = '';
        document.getElementById('searchGainianInput').value = '';
        // 重置下拉选择框
        document.getElementById('rankChangeSelect').value = '';
        document.getElementById('limitupSelect').value = 'all';
        document.getElementById('currentRankSelect').value = ''; // 重置新排名选择框

        document.getElementById('strategySelect').value = '';

        // 重置所有下拉选择框为"全部"选项
        document.querySelector('select[onchange="setChangePercentFilter(this.value)"]').value = 'all';
        document.querySelector('select[onchange="setMainCapitalFlow1dFilter(this.value)"]').value = 'mainAll';
        document.querySelector('select[onchange="setProfitFilter(this.value)"]').value = 'profitAll';
        document.querySelector('select[onchange="setMarketValueFilter(this.value)"]').value = 'marketAll';
        document.querySelector('select[onchange="setTurnoverRateFilter(this.value)"]').value = 'turnoverAll'; // 重置换手率选择框
        document.querySelector('select[onchange="setVolumeFilter(this.value)"]').value = 'volumeAll'; // 重置成交量选择框
        document.querySelector('select[onchange="setRsiFilter(this.value)"]').value = 'rsiAll'; // 重置RSI选择框
        document.querySelector('select[onchange="setMarketSegmentFilter(this.value)"]').value = 'all'; // 重置市场板块选择框（新增）

        // 重新应用过滤并刷新表格
        filterByAllConditions();
        currentPage = 1; // 重置到第一页
        renderTable();
        // 显示重置成功提示
        showResetSuccessToast();
    }


    // 显示重置成功的提示
    function showResetSuccessToast() {
        // 创建提示元素
        const toast = document.createElement('div');
        toast.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        background: #007bff;
        color: white;
        padding: 12px 20px;
        border-radius: 6px;
        box-shadow: 0 4px 12px rgba(0,0,0,0.3);
        z-index: 9999;
        font-size: 12px;
        font-weight: 500;
        display: flex;
        align-items: center;
        gap: 8px;
        opacity: 0;
        transform: translateX(100%);
        transition: all 0.3s ease;
    `;

        toast.innerHTML = `
        <i class="fa fa-check-circle" aria-hidden="true"></i>
        所有过滤条件已重置
    `;

        document.body.appendChild(toast);

        // 动画显示
        setTimeout(() => {
            toast.style.opacity = '1';
            toast.style.transform = 'translateX(0)';
        }, 100);

        // 2秒后自动隐藏
        setTimeout(() => {
            toast.style.opacity = '0';
            toast.style.transform = 'translateX(100%)';
            setTimeout(() => {
                if (document.body.contains(toast)) {
                    document.body.removeChild(toast);
                }
            }, 300);
        }, 2000);
    }


    // 设置1天主力资金过滤条件
    function setMainCapitalFlow1dFilter(filterType) {
        // 更新过滤条件
        mainCapitalFlow1dFilter = filterType;

        // 应用过滤并重置分页
        filterByAllConditions();
        currentPage = 1;
        renderTable();
    }

    // 设置涨幅过滤条件
    function setChangePercentFilter(filterType) {
        // 设置过滤条件
        changePercentFilter = filterType;

        // 应用过滤
        filterByAllConditions();
        currentPage = 1;
        renderTable();
    }

    // 初始化表头点击排序
    function initSortableHeaders() {
        // 为所有可排序表头添加点击事件
        document.querySelectorAll('th.sortable-header').forEach(header => {
            header.addEventListener('click', handleHeaderClick);
        });
    }

    // 表头点击处理函数
    function handleHeaderClick(e) {
        const sortField = e.currentTarget.dataset.sort;

        // 如果点击的是当前排序字段，则切换排序方向
        if (currentSortField === sortField) {
            currentSortDirection = currentSortDirection === 'asc' ? 'desc' : 'asc';
        } else {
            // 否则设置新的排序字段，默认升序
            currentSortField = sortField;
            currentSortDirection = 'desc';
        }

        // 执行排序
        sortData();

        // 更新排序指示器
        updateSortIndicators();

        // 重置分页并重新渲染
        currentPage = 1;
        renderTable();
    }

    // 更新排序指示器
    function updateSortIndicators() {
        // 清除所有指示器
        document.querySelectorAll('.sort-indicator').forEach(indicator => {
            indicator.textContent = '';
        });

        // 为当前排序字段添加指示器
        if (currentSortField) {
            const indicator = document.querySelector(`th[data-sort="${currentSortField}"] .sort-indicator`);
            indicator.textContent = currentSortDirection === 'desc' ? '↓' : '↑';
        }
    }

    // 执行数据排序
    function sortData() {
        if (!currentSortField) return;

        filteredData.sort((a, b) => {
            // 处理排名变化的特殊情况
            if (currentSortField === 'rankChange') {
                const aDiff = a.currentOldRankPosition - a.currentRankPosition;
                const bDiff = b.currentOldRankPosition - b.currentRankPosition;
                return currentSortDirection === 'asc' ? aDiff - bDiff : bDiff - aDiff;
            }

            // 处理获利排序的特殊情况
            if (currentSortField === 'getmainCost') {
                // 计算获利百分比
                const aProfit = calculateProfitPercent(a.price, a.mainCost);
                const bProfit = calculateProfitPercent(b.price, b.mainCost);
                return currentSortDirection === 'asc' ? aProfit - bProfit : bProfit - aProfit;
            }

            // 获取比较值
            let valueA = a[currentSortField];
            let valueB = b[currentSortField];

            // 处理null值
            if (valueA === null || valueA === undefined) valueA = "";
            if (valueB === null || valueB === undefined) valueB = "";

            // 数字比较
            if (!isNaN(valueA) && !isNaN(valueB)) {
                return currentSortDirection === 'asc' ? Number(valueA) - Number(valueB) : Number(valueB) - Number(valueA);
            }

            // 字符串比较
            if (typeof valueA === 'string' && typeof valueB === 'string') {
                const compareResult = valueA.localeCompare(valueB, 'zh-CN');
                return currentSortDirection === 'asc' ? compareResult : -compareResult;
            }

            // 默认比较
            return 0;
        });
    }

    // 计算获利百分比的辅助函数
    function calculateProfitPercent(price, mainCost) {
        const nowPrice = Number(price);
        const costPrice = Number(mainCost);

        if (isNaN(nowPrice) || isNaN(costPrice) || !isFinite(nowPrice) || !isFinite(costPrice) || costPrice <= 0) {
            return 0; // 无效值视为0%
        }

        return ((nowPrice - costPrice) / costPrice) * 100;
    }

    // 更新最后更新时间
    function updateLastUpdateTime() {
        const formatTime = (createdAt) => {
            if (!createdAt) return '-';
            return new Date(createdAt).toLocaleString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit'
            });
        };
        document.getElementById('lastUpdateTime').textContent = `最后更新:${formatTime(createdAt)}`;
    }

    function addupdateFocusStocks(type) {
        // 获取选中的股票代码并处理
        var focusStocks = $('input[name="select-stockCode"]:checked').map(function() {
            return $(this).val();
        }).get().join(',');

        // 验证选择
        if (!focusStocks || focusStocks.trim() === '') {
            alert('没有选择股票代码');
            return;
        }
        // 处理股票代码格式
        focusStocks = focusStocks.split('\n').join(',');

        // 根据type构建不同的请求参数
        var requestData = {};
        switch(type) {
            case '1':
                // 关注类型：传递focusStocks参数
                requestData.focusStocks = focusStocks;
                break;
            case '2':
                // 可选类型：传递allOptional参数
                requestData.allOptional = focusStocks;
                break;
            default:
                // 默认情况或错误类型处理
                alert('无效的操作类型');
                return;
        }

        // 发送AJAX请求
        $.ajax({
            url: '/sysinfo/appendBy',
            method: 'GET',
            data: requestData, // 使用根据type构建的参数
            success: function (response) {
                alert('操作成功');
            },
            error: function (xhr, status, error) {
                console.error('操作失败:', error);
                $('#loadingIndicator').removeClass('active');
                if (typeof reject === 'function') {
                    reject(error);
                }
            }
        });
    }

    // 更新统计数据显示
    function updateStats() {
        // 获取页面上的统计元素
        const totalEl = document.getElementById('allCount');
        const upEl = document.getElementById('upCount');
        const downEl = document.getElementById('downCount');
        const pinEl = document.getElementById('pinCount');
        const limitUpEl = document.getElementById('limitUpCount');
        const limitDownEl = document.getElementById('limitDownCount');
        const flowGainianEL = document.getElementById('flowGainian');

        // 更新元素内容（如果数据存在则显示，否则显示"-"）
        totalEl.textContent = allstocks !== undefined ? allstocks : '-';
        upEl.textContent = stocksUP !== undefined ? stocksUP : '-';
        downEl.textContent = stocksDown !== undefined ? stocksDown : '-';
        pinEl.textContent = stocksPin !== undefined ? stocksPin : '-';
        limitUpEl.textContent = stocksLimit !== undefined ? stocksLimit : '-';
        limitDownEl.textContent = stocksLimitDown !== undefined ? stocksLimitDown : '-';
        flowGainianEL.textContent = flowGainian !== undefined ? flowGainian : '-';

        const todayAllEL = document.getElementById('todayAll');
        todayAllEL.innerHTML = todayAll !== undefined ? formatNumbers(todayAll) : '-';

        const todayAllMainEL = document.getElementById('todayAllMain');
        todayAllMainEL.innerHTML = todayAllMain !== undefined ? formatNumbers(todayAllMain) : '-';
    }

    const formatNumbers = (num) => {
        if (num === null || num === undefined) return '0.00';

        // 转换为亿元（除以10000万）
        const value = Number(num) / 10000 / 10000;
        const formattedValue = value.toLocaleString('zh-CN', {
            maximumFractionDigits: 2,
            minimumFractionDigits: 2, // 确保始终显示2位小数
            useGrouping: false // 禁用千位分隔符
        });

        // 安全转义HTML特殊字符
        const escapedValue = formattedValue
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;');

        // 根据数值正负设置颜色（正数红色，负数绿色）
        if (value > 0) {
            return `<span class="text-red-500">${escapedValue}</span>`;
        } else if (value < 0) {
            return `<span class="text-green-500">${escapedValue}</span>`;
        }
        return escapedValue; // 0值默认颜色
    };

    function removeupdateFocusStock() {
        var focusStocks = $('input[name="select-stockCode"]:checked').map(function() {
            return $(this).val();
        }).get().join(',');

        if (!focusStocks || focusStocks.trim() === '') {
            alert('没有选择股票代码');
            return;
        }

        focusStocks=(focusStocks ? focusStocks.split('\n').join(',') : '');
        $.ajax({
            url: '/sysinfo/removeBy',
            method: 'GET',
            data: {
                focusStocks: focusStocks
            },
            success: function (response) {
                alert('取消关注成功');
            },
            error: function (xhr, status, error) {
                console.error('概念查询失败:', error);
                $('#loadingIndicator').removeClass('active');
                reject(error);
            }
        });
    }

    // 加载股票数据
    function loadStockData() {
        fetch('/stocksflow/summary')
            .then(response => {
                if (!response.ok) {
                    throw new Error('网络响应不正常');
                }
                return response.json();
            })
            .then(data => {
                stockData = data.result;
                flowStock = data.flowStock;
                todayAll = data.todayAll;
                todayAllMain = data.todayAllMain;
                createdAt = data.createdAt;
                todaylimitstr = data.todaylimitstr;
                todaylimitcontinuousstr = data.todaylimitcontinuousstr;
                limit10dstr = data.limit10dstr;
                searchtr = data.searchtr;
                notlimit10dstr = data.notlimit10dstr;
                review15dstr = data.review15dstr;
                allOptional = data.allOptional;
                onlyFlowStock = data.onlyFlowStock;
                flowGainian = data.flowGainian;
                filteredData = [...stockData];
                currentPage = 1;

                allstocks = data.allstocks ;
                stocksUP =data.stocksUP;
                stocksDown = data.stocksDown;
                stocksPin = data.stocksPin;
                stocksLimit = data.stocksLimit;
                stocksLimitDown = data.stocksLimitDown;

                // 更新统计数据显示
                updateStats();

                filterByAllConditions();

                // 应用默认排序
                sortData();
                updateSortIndicators();
                renderTable();
                updateLastUpdateTime();
            })
            .catch(error => {
                console.error('获取数据时出错:', error);
                document.getElementById('stockTableBody').innerHTML = `
                        <tr>
                            <td colspan="27" class="px-4 py-8 text-center text-red-500">
                                <p>加载数据失败: ${error.message}</p>
                                <button onclick="loadStockData()" class="mt-2 text-primary hover:underline">重试</button>
                            </td>
                        </tr>
                    `;
            });
    }

    // 加载策略数据
    function loadStrategyData() {
        fetch('/sysinfo/getCheckSys')
            .then(response => {
                if (!response.ok) {
                    throw new Error('网络响应不正常');
                }
                return response.json();
            })
            .then(data => {
                if (data.success && data.checksysInfos) {
                    const strategySelect = document.getElementById('strategySelect');
                    // 清空现有选项（保留默认选项）
                    strategySelect.innerHTML = '<option value="">选择策略</option>';

                    // 添加策略选项
                    data.checksysInfos.forEach(strategy => {
                        const option = document.createElement('option');
                        option.value = strategy.sysValue;
                        option.textContent = strategy.sysKey;
                        strategySelect.appendChild(option);
                    });
                }
            })
            .catch(error => {
                console.error('加载策略数据时出错:', error);
            });
    }

    // 核心过滤函数 - 确保所有条件同时生效
    function filterByAllConditions() {
        const searchTerm = document.getElementById('searchInput').value;
        // 获取趋势选择值
        let rankChangeInputTerm = document.getElementById('rankChangeSelect').value;

        filteredData = stockData.filter(stock => {
            // 条件1：满足代码/名称搜索（如果搜索词为空，则默认满足）
            const stockCode = stock.code == null ? "--" : stock.code.toLowerCase();
            const stockName = stock.name == null ? "--" : stock.name.toLowerCase();
            const stockNamepy = stock.namepy == null ? "--" : stock.namepy.toLowerCase();
            let matchSearch = false;
            // 检查searchTerm是否存在且包含空格
            const hasSpaces = searchTerm !== null && searchTerm.includes(' ');

            if (searchTerm === '=') {
                matchSearch = flowStock && flowStock.includes(stock.code);
            } else if (searchTerm === '-') {
                matchSearch = onlyFlowStock && onlyFlowStock.includes(stock.code);
            } else if (searchTerm === '+') {
                matchSearch = allOptional && allOptional.includes(stock.code);
            }else if (hasSpaces) {
                // 处理空格分割的情况：转换为逗号并取两个集合的对称差
                const processedSearchTerm = searchTerm.replace(/\s+/g, ',');

                // 将字符串分割为数组并过滤空值
                const flowStockArray = flowStock ? flowStock.split(',').filter(Boolean) : [];
                const searchArray = processedSearchTerm.split(',').filter(Boolean);

                // 计算对称差：只保留两个数组中互不包含的元素
                // 1. flowStock中有但searchArray中没有的元素
                const diff1 = flowStockArray.filter(code => !searchArray.includes(code));
                // 2. searchArray中有但flowStock中没有的元素
                const diff2 = searchArray.filter(code => !flowStockArray.includes(code));
                // 合并对称差结果
                const symmetricDiff = [...diff1, ...diff2];

                // 仅判断当前股票代码是否在对称差集合中
                // matchSearch = symmetricDiff.includes(stock.code);

                // 保留原有的其他匹配条件（基于处理后的搜索词）
                matchSearch =
                    stockCode.includes(symmetricDiff) ||
                    symmetricDiff.includes(stockCode) ||
                    stockName.includes(symmetricDiff) ||
                    symmetricDiff.includes(stockName) ||
                    stockNamepy.includes(symmetricDiff);
            } else {
                matchSearch = searchTerm === ''
                    ? true
                    : stockCode.includes(searchTerm) ||
                    searchTerm.includes(stockCode) ||
                    stockName.includes(searchTerm) ||
                    searchTerm.includes(stockName) ||
                    stockNamepy.includes(searchTerm);
            }

            // 条件2：满足概念搜索（如果搜索词为空，则默认满足）
            // 处理股票概念，确保为字符串类型
            const stockConcept = stock.concept == null ? "--" : stock.concept.toLowerCase();
            let matchGainian = false;

            let searchGainianTerm = document.getElementById('searchGainianInput').value;
            if (searchGainianTerm === '=') {
                searchGainianTerm = flowGainian;
            }

            if (searchGainianTerm === '') {
                matchGainian = true;
            } else {
                // 处理概念搜索词：分割、去空格、过滤空项
                const searchTerms = searchGainianTerm.toLowerCase()
                    .split(',')
                    .map(term => term.trim())
                    .filter(Boolean); // 过滤空字符串

                // 将股票概念按逗号分割、去空格、过滤空项
                const stockConcepts = stockConcept
                    .split(';')
                    .map(concept => concept.trim())
                    .filter(Boolean); // 过滤空字符串

                // 精确匹配：搜索词与股票概念完全相同
                matchGainian = stockConcepts.some(term =>
                    searchTerms.some(concept => concept === term)
                );
            }

            // 条件3：满足涨幅过滤条件
            let matchChangePercent = true;
            const changePercent = Number(stock.changePercent) || 0;


            switch (changePercentFilter) {
                case 'up5':
                    matchChangePercent = changePercent >= 5;
                    break;
                case 'up3':
                    matchChangePercent = changePercent >= 3;
                    break;
                case 'up0-3':
                    matchChangePercent = (changePercent <= 3 && changePercent > 0);
                    break;
                case 'up1':
                    matchChangePercent = changePercent >= 1;
                    break;
                case 'up0':
                    matchChangePercent = changePercent > 0;
                    break;
                case 'down1':
                    matchChangePercent = changePercent < -1;
                    break;
                case 'down3':
                    matchChangePercent = changePercent < -3;
                    break;
                case 'down5':
                    matchChangePercent = changePercent < -5;
                    break;
                case 'limitUp':
                    // 假设涨停为涨幅>=9.8%
                    matchChangePercent = changePercent >= 9.8;
                    break;
                case 'limitDown':
                    // 假设跌停为跌幅<=-9.8%
                    matchChangePercent = changePercent <= -9.8;
                    break;
                case 'all':
                default:
                    matchChangePercent = true;
            }

            // 条件4：满足趋势条件
            let matchRankChange = true;
            // 将选择值转换为数字类型
            const rankChangeThreshold = rankChangeInputTerm ? Number(rankChangeInputTerm) : null;
            const currentRank = Number(stock.currentRankPosition);
            const oldRank = Number(stock.currentOldRankPosition);
            const change = oldRank - currentRank; // 排名变化值（旧排名 - 新排名）

            // 如果选择了有效的阈值，则进行判断
            if (rankChangeThreshold !== null && !isNaN(rankChangeThreshold)) {
                matchRankChange = (rankChangeThreshold > 0 && change >= rankChangeThreshold) ||
                    (rankChangeThreshold <= 0 && change <= rankChangeThreshold);
            }

            // 条件5：1天主力资金过滤
            let matchMainCapitalFlow1d = true;
            // 转换单位为“亿”（与表格显示一致）
            const mainFlow1d = (stock.mainCapitalFlow1d || 0) / 10000 / 10000;
            const capital = (stock.capitalFlow1d || 0) / 10000 / 10000;
            switch (mainCapitalFlow1dFilter) {
                case 'mainIn0': matchMainCapitalFlow1d = (mainFlow1d < 0 && capital > mainFlow1d); break; // 主力流出散户流入
                case 'mainIn00': matchMainCapitalFlow1d = (mainFlow1d >= 0.001 && mainFlow1d>=capital); break; // 主力流入散户流出
                case 'mainIn6': matchMainCapitalFlow1d = (mainFlow1d >= 0.001 && capital > 0 && (mainFlow1d / capital) > 0.6); break; // 主力流入占6成
                case 'mainIn01': matchMainCapitalFlow1d = mainFlow1d >= 0.01; break; // 流入>0.01亿
                case 'mainIn05': matchMainCapitalFlow1d = mainFlow1d >= 0.5; break; // 流入>0.5亿
                case 'mainIn1': matchMainCapitalFlow1d = mainFlow1d >= 1; break;    // 流入>1亿
                case 'mainIn5': matchMainCapitalFlow1d = mainFlow1d >= 5; break;    // 流入>5亿
                case 'mainOut0': matchMainCapitalFlow1d = (mainFlow1d < 0 && capital > -1); break;  // 流出>1亿（负值）
                case 'mainOut1': matchMainCapitalFlow1d = mainFlow1d <= -1; break;  // 流出>1亿（负值）
                case 'mainOut5': matchMainCapitalFlow1d = mainFlow1d <= -5; break;  // 流出>5亿（负值）
                default: matchMainCapitalFlow1d = true; // 全部
            }

            // 条件6：获利过滤条件
            let matchProfit = true;
            const profitPercent = calculateProfitPercent(stock.price, stock.mainCost);

            switch (profitFilter) {
                case 'profitUp20':
                    matchProfit = profitPercent >= 20; // 获利≥20%
                    break;
                case 'profitUp10':
                    matchProfit = profitPercent >= 10 && profitPercent < 20; // 获利10%~20%（不含20%）
                    break;
                case 'profitUp5':
                    matchProfit = profitPercent >= 5 && profitPercent < 10; // 获利5%~10%（不含10%）
                    break;
                case 'profitUp0':
                    matchProfit = profitPercent >= 0 && profitPercent < 5; // 获利0%~5%（不含5%）
                    break;
                case 'profitUp00':
                    matchProfit = profitPercent > 0; // 获利>0
                    break;
                case 'profitDown0':
                    matchProfit = profitPercent < 0 && profitPercent > -5; // 获利-5%~0%（不含0%和-5%）
                    break;
                case 'profitDown5':
                    matchProfit = profitPercent <= -5 && profitPercent > -10; // 获利-10%~-5%（不含-10%）
                    break;
                case 'profitDown10':
                    matchProfit = profitPercent <= -10; // 获利≤-10%
                    break;
                case 'profitAll':
                default:
                    matchProfit = true; // 全部
            }

            // 条件7：15天有涨停过滤
            let matchLimitup = true;
            // 检查股票代码是否在涨停列表或非涨停列表中
            const isInLimitList = limit10dstr && limit10dstr.includes(stock.code);
            const isInNotLimitList = notlimit10dstr && notlimit10dstr.includes(stock.code);
            const isInTodayLimitList = todaylimitstr + "," + todaylimitcontinuousstr && (todaylimitstr + "," + todaylimitcontinuousstr).includes(stock.code);
            const isInTodayLimitListCont = todaylimitcontinuousstr && (todaylimitcontinuousstr).includes(stock.code);
            const isInTodayLimitListFirst = todaylimitstr && (todaylimitstr).includes(stock.code);
            const isInsearchList = searchtr && searchtr.includes(stock.code);
            const isInreviewList = review15dstr && review15dstr.includes(stock.code);

            switch (limitupFilter) {
                case 'yes':
                    // 只显示15天内有涨停的股票
                    matchLimitup = isInLimitList;
                    break;
                case 'no':
                    // 只显示15天内没有涨停的股票
                    matchLimitup = isInNotLimitList;
                    break;
                case 'today':
                    // 只显示今天涨停的股票
                    matchLimitup = isInTodayLimitList;
                    break;
                case 'todayF':
                    // 只显示今天首板涨停的股票
                    matchLimitup = isInTodayLimitListFirst;
                    break;
                case 'todayCont':
                    // 只显示今天连板涨停的股票
                    matchLimitup = isInTodayLimitListCont;
                    break;
                case 'search':
                    // 只显示自选涨停的股票
                    matchLimitup = isInsearchList;
                    break;
                case 'review':
                    // 只显示自选涨停的股票
                    matchLimitup = isInreviewList;
                    break;
                case 'all':
                default:
                    // 显示全部
                    matchLimitup = true;
            }

            // 条件8：新排名过滤
            let matchCurrentRank = true;
            const currentRankValue = Number(stock.currentRankPosition);
            const rankThreshold = currentRankFilter ? Number(currentRankFilter) : null;

            if (rankThreshold !== null && !isNaN(rankThreshold) && rankThreshold > 0) {
                // 只显示排名在前N名的股票（排名值越小表示越靠前）
                matchCurrentRank = !isNaN(currentRankValue) && currentRankValue <= rankThreshold;
            }

            // 条件9：市值过滤
            let matchMarketValue = true;
            // 市值单位是亿
            const marketValue = Number(stock.marketValue) / 10000 / 10000;

            switch (marketValueFilter) {
                case 'marketLt50':
                    matchMarketValue = marketValue < 50; // 市值<50亿
                    break;
                case 'marketLt100':
                    matchMarketValue = marketValue < 100; // 市值<100亿
                    break;
                case 'market100':
                    matchMarketValue = (marketValue >= 100 && marketValue<500); // 市值>100亿
                    break;
                case 'market500':
                    matchMarketValue = (marketValue >= 500 && marketValue<1000); // 市值>500亿
                    break;
                case 'market1000':
                    matchMarketValue = marketValue > 1000; // 市值>1000亿
                    break;
                case 'market5000':
                    matchMarketValue = marketValue > 5000; // 市值>5000亿
                    break;
                case 'market10000':
                    matchMarketValue = marketValue > 10000; // 市值>1万亿
                    break;
                case 'marketAll':
                default:
                    matchMarketValue = true; // 全部
            }

            // 条件10：换手率过滤
            let matchTurnoverRate = true;
            const turnoverRate = Number(stock.turnoverRate) || 0;

            switch (turnoverRateFilter) {
                case 'turnoverLt1':
                    matchTurnoverRate = turnoverRate < 1; // 换手率<1%
                    break;
                case 'turnover1To3':
                    matchTurnoverRate = turnoverRate >= 1 && turnoverRate < 3; // 换手率1-3%
                    break;
                case 'turnover3To5':
                    matchTurnoverRate = turnoverRate >= 3 && turnoverRate < 5; // 换手率3-5%
                    break;
                case 'turnover5To10':
                    matchTurnoverRate = turnoverRate >= 5 && turnoverRate < 10; // 换手率5-10%
                    break;
                case 'turnover10To20':
                    matchTurnoverRate = turnoverRate >= 10 && turnoverRate < 20; // 换手率10-20%
                    break;
                case 'turnoverGt20':
                    matchTurnoverRate = turnoverRate >= 20; // 换手率>20%
                    break;
                case 'turnoverAll':
                default:
                    matchTurnoverRate = true; // 全部
            }

            // 条件11：成交量过滤
            let matchVolume = true;
            // 成交量单位是百万
            const volume = Number(stock.volume) / 1000000 || 0;

            switch (volumeFilter) {
                case 'volumeLt10':
                    matchVolume = volume < 10; // 成交量<10百万
                    break;
                case 'volume10To50':
                    matchVolume = volume >= 10 && volume < 50; // 成交量10-50百万
                    break;
                case 'volume50To100':
                    matchVolume = volume >= 50 && volume < 100; // 成交量50-100百万
                    break;
                case 'volume100To500':
                    matchVolume = volume >= 100 && volume < 500; // 成交量100-500百万
                    break;
                case 'volume500To1000':
                    matchVolume = volume >= 500 && volume < 1000; // 成交量500-1000百万
                    break;
                case 'volumeGt1000':
                    matchVolume = volume >= 1000; // 成交量>1000百万
                    break;
                case 'volumeAll':
                default:
                    matchVolume = true; // 全部
            }

            // 条件12：RSI过滤
            let matchRsi = true;
            const rsi = Number(stock.rsi6) || 0;

            switch (rsi6Filter) {
                case 'rsiLt30':
                    matchRsi = rsi < 30; // RSI<30（超卖）
                    break;
                case 'rsi30To50':
                    matchRsi = rsi >= 30 && rsi < 50; // RSI30-50
                    break;
                case 'rsi50To70':
                    matchRsi = rsi >= 50 && rsi < 70; // RSI50-70
                    break;
                case 'rsiGt70':
                    matchRsi = rsi >= 70; // RSI>70（超买）
                    break;
                case 'rsiAll':
                default:
                    matchRsi = true; // 全部
            }

            // 条件13：市场板块过滤（新增）
            let matchMarketSegment = true;
            const code = stock.code || '';

            switch (marketSegmentFilter) {
                case 'main': // 主板：60开头的沪市主板、000开头的深市主板
                    matchMarketSegment = code.startsWith('60') || code.startsWith('0');
                    break;
                case 'growth': // 创业板：300开头
                    matchMarketSegment = code.startsWith('3');
                    break;
                case 'tech': // 科创板：688开头
                    matchMarketSegment = code.startsWith('68');
                    break;
                case 'st': // ST股：名称包含ST
                    matchMarketSegment = (stock.name || '').includes('ST');
                    break;
                case 'north': // 北交所：8开头
                    matchMarketSegment = code.startsWith('8') || code.startsWith('4')  || code.startsWith('9') ;
                    break;
                case 'all':
                default:
                    matchMarketSegment = true; // 全部
            }

            // 关键：所有条件必须同时满足（使用逻辑与连接）
            return matchSearch &&
                matchGainian &&
                matchChangePercent &&
                matchRankChange &&
                matchMainCapitalFlow1d &&
                matchProfit &&
                matchLimitup &&
                matchCurrentRank &&
                matchMarketValue &&
                matchTurnoverRate &&
                matchVolume &&
                matchRsi &&
                matchMarketSegment; // 新增市场板块过滤条件

        });
    }


    // 刷新数据
    function refreshData() {
        const refreshBtn = document.getElementById('refreshBtn');
        const originalHtml = refreshBtn.innerHTML;

        // 显示加载状态
        refreshBtn.innerHTML = '<i class="fa fa-refresh fa-spin" aria-hidden="true"></i><span>加载中...</span>';
        refreshBtn.disabled = true;

        // 清空表格并显示加载状态
        document.getElementById('stockTableBody').innerHTML = `
                <tr>
                    <td colspan="27" class="px-4 py-8 text-center text-gray-500">
                        <div class="flex flex-col items-center">
                            <i class="fa fa-circle-o-notch fa-spin text-2xl mb-2" aria-hidden="true"></i>
                            <p>正在刷新数据...</p>
                        </div>
                    </td>
                </tr>
            `;

        // 构建查询参数
        const startDate = document.getElementById('startDate').value;
        const params = new URLSearchParams();
        if (startDate) params.append('startDate', startDate);

        // 重新加载数据
        fetch(`/stocksflow/summary?${params.toString()}`)
            .then(response => {
                if (!response.ok) {
                    throw new Error('网络响应不正常');
                }
                return response.json();
            })
            .then(data => {
                stockData = data.result;
                flowStock = data.flowStock;
                todayAll = data.todayAll;
                todayAllMain = data.todayAllMain;
                createdAt = data.createdAt;
                todaylimitstr = data.todaylimitstr;
                todaylimitcontinuousstr = data.todaylimitcontinuousstr;
                limit10dstr = data.limit10dstr;
                searchtr = data.searchtr;
                notlimit10dstr = data.notlimit10dstr;

                allOptional = data.allOptional;
                onlyFlowStock = data.onlyFlowStock;
                flowGainian = data.flowGainian;
                filteredData = [...stockData];
                currentPage = 1;

                allstocks = data.allstocks ;
                stocksUP =data.stocksUP;
                stocksDown = data.stocksDown;
                stocksPin = data.stocksPin;
                stocksLimit = data.stocksLimit;
                stocksLimitDown = data.stocksLimitDown;

                // 更新统计数据显示
                updateStats();

                filterByAllConditions();
                // 应用当前排序
                sortData();

                renderTable();

                updateLastUpdateTime();

                // 恢复按钮状态
                refreshBtn.innerHTML = originalHtml;
                refreshBtn.disabled = false;
            })
            .catch(error => {
                console.error('刷新数据时出错:', error);
                document.getElementById('stockTableBody').innerHTML = `
                        <tr>
                            <td colspan="16" class="px-4 py-8 text-center text-red-500">
                                <p>刷新数据失败: ${error.message}</p>
                                <button onclick="refreshData()" class="mt-2 text-primary hover:underline">重试</button>
                            </td>
                        </tr>
                    `;

                // 恢复按钮状态
                refreshBtn.innerHTML = originalHtml;
                refreshBtn.disabled = false;
            });
    }

    // 提取样式判断逻辑为独立函数
    function getStockNameStyle(stock) {
        // 先判断是否为allOptional，优先级更高
        if (allOptional && allOptional.split(',').includes(stock.code)) {
            return 'background-color: #FF0000;';
        }
        // 再判断是否为flowStock
        if (flowStock && flowStock.split(',').includes(stock.code)) {
            return 'background-color: #FFFF00;';
        }
        // 默认无特殊样式
        return '';
    }


    // 渲染表格
    function renderTable() {
        const tableBody = document.getElementById('stockTableBody');
        const startIndex = (currentPage - 1) * pageSize;
        const endIndex = Math.min(startIndex + pageSize, filteredData.length);
        const pageData = filteredData.slice(startIndex, endIndex);

        // 更新计数信息
        document.getElementById('shownCount').textContent = pageData.length;
        document.getElementById('totalCount').textContent = filteredData.length;

        // 更新分页按钮状态
        document.getElementById('prevPage').disabled = currentPage === 1;
        document.getElementById('nextPage').disabled = endIndex >= filteredData.length;

        if (pageData.length === 0) {
            tableBody.innerHTML = `<tr>
                        <td colspan="27" class="px-4 py-8 text-center text-gray-500">
                            <p>没有找到匹配的数据</p>
                        </td>
                    </tr>`;
            return;
        }

        // 生成表格内容
        let html = '';
        pageData.forEach(stock => {
            // 计算排名变化
            const rankChange = calculateRankChange(stock.currentRankPosition, stock.currentOldRankPosition);

            html += `
                <tr class="border-t border-gray-200 hover:bg-yellow-100 transition-colors">
                    <td class="px-4 py-3 text-sm "><input type="checkbox" class="row-checkbox" name="select-stockCode" value="${stock.code || ''}" data-id="${stock.code || ''}"></td>
                    <td class="px-4 py-3 text-sm" onclick="openSelectedStockCodes('${stock.code || ''}')">${stock.code}</td>
                    <td class="px-4 py-3 text-base " onclick="openSelectedStockCodes('${stock.code || ''}')" style="${getStockNameStyle(stock)}">
                        ${stock.name}
                    </td>
                    <td class="px-2 py-3 text-sm ${formatNumberClass(stock.mainCapitalFlow1d/10000/10000)}" style="background-color: #DFD3B9;">${formatNumber(stock.mainCapitalFlow1d/10000/10000)}</td>
                    <td class="px-2 py-3 text-sm ${formatNumberClass(stock.capitalFlow1d/10000/10000)}">${formatNumber(stock.capitalFlow1d/10000/10000)}</td>

                    <td class="px-2 py-3 text-sm  ${formatNumberClass(stock.mainCapitalFlow2d/10000/10000)}" style="background-color: #DFD3B9;">${formatNumber(stock.mainCapitalFlow2d/10000/10000)}</td>
                    <td class="px-2 py-3 text-sm  ${formatNumberClass(stock.capitalFlow2d/10000/10000)}">${formatNumber(stock.capitalFlow2d/10000/10000)}</td>

                    <td class="px-2 py-3 text-sm  ${formatNumberClass(stock.mainCapitalFlow3d/10000/10000)}" style="background-color: #DFD3B9;">${formatNumber(stock.mainCapitalFlow3d/10000/10000)}</td>
                    <td class="px-2 py-3 text-sm  ${formatNumberClass(stock.capitalFlow3d/10000/10000)}">${formatNumber(stock.capitalFlow3d/10000/10000)}</td>

                    <td class="px-2 py-3 text-sm  ${formatNumberClass(stock.mainCapitalFlow5d/10000/10000)}" style="background-color: #DFD3B9;">${formatNumber(stock.mainCapitalFlow5d/10000/10000)}</td>
                    <td class="px-2 py-3 text-sm  ${formatNumberClass(stock.capitalFlow5d/10000/10000)}">${formatNumber(stock.capitalFlow5d/10000/10000)}</td>

                    <td class="px-2 py-3 text-sm  ${formatNumberClass(stock.mainCapitalFlow6d/10000/10000)}" style="background-color: #DFD3B9;">${formatNumber(stock.mainCapitalFlow6d/10000/10000)}</td>
                    <td class="px-2 py-3 text-sm  ${formatNumberClass(stock.capitalFlow6d/10000/10000)}">${formatNumber(stock.capitalFlow6d/10000/10000)}</td>

                    <td class="px-2 py-3 text-sm  ${formatNumberClass(stock.mainCapitalFlow7d/10000/10000)}" style="background-color: #DFD3B9;">${formatNumber(stock.mainCapitalFlow7d/10000/10000)}</td>
                    <td class="px-2 py-3 text-sm  ${formatNumberClass(stock.capitalFlow7d/10000/10000)}">${formatNumber(stock.capitalFlow7d/10000/10000)}</td>

                    <td class="px-2 py-3 text-sm  sm:text-right">${formatNumber(stock.marketValue/10000/10000)}</td>

                    <td class="px-4 py-3 text-sm  ${formatNumberClass(stock.price)}">${formatNumber(stock.price)}</td>
                    <td class="px-4 py-3 text-sm  " style="background-color: #DFD3B9;">${formatNumber(stock.mainCost)}</td>
                    <td class="px-4 py-3 text-sm  ${getMainProfit(stock.price, stock.mainCost).class}" style="background-color: #DFD3B9;">${getMainProfit(stock.price, stock.mainCost).html}</td>
                    <td class="px-4 py-3 text-sm  ${formatNumberClass(stock.changePercent)}">${formatNumber(stock.changePercent)}%</td>
                    <td class="px-4 py-3 text-sm  ">${formatNumber(stock.volume/1000000)}</td>
                    <td class="px-4 py-3 text-sm  ">${formatNumber(stock.turnoverRate)}</td>
                    <td class="px-4 py-3 text-sm  ">${formatNumber(stock.rsi6)}</td>
                    <td class="px-4 py-3 text-base "
                        ${formatConcept(stock.concept).title ? `title="${formatConcept(stock.concept).title}"` : ''}>
                        ${formatConcept(stock.concept).display}
                    </td>
                    <td class="px-4 py-3 text-sm ">${stock.currentRankPosition || '-'}</td>
                    <td class="px-4 py-3 text-sm ">${stock.currentOldRankPosition || '-'}</td>
                    <td class="px-4 py-3 text-sm  ${rankChange.class}">${rankChange.html}</td>
                </tr>
                `;
        });
        tableBody.innerHTML = html;
    }


    // 全选/取消全选功能实现
    function setupCheckboxHandler() {
        // 获取全选复选框元素
        const selectAllCheckbox = document.getElementById('select-all');
        // 获取所有行复选框
        const rowCheckboxes = document.querySelectorAll('input[name="select-stockCode"]');
        // 全选复选框变更事件
        selectAllCheckbox.addEventListener('change', function() {
            // 将所有行复选框的状态设置为与全选复选框一致
            rowCheckboxes.forEach(checkbox => {
                checkbox.checked = this.checked;
            });
        });
        // 监听行复选框的变化，更新全选框状态
        rowCheckboxes.forEach(checkbox => {
            checkbox.addEventListener('change', function() {
                // 检查所有行复选框是否都被选中
                const allChecked = Array.from(rowCheckboxes).every(cb => cb.checked);
                selectAllCheckbox.checked = allChecked;
            });
        });
    }


    // 处理代码/名称搜索
    function handleSearch(e) {
        filterByAllConditions();
        currentPage = 1;
        renderTable();
    }

    // 处理概念搜索
    function handleSearchGainian(e) {
        filterByAllConditions();
        currentPage = 1;
        renderTable();
    }

    // 处理趋势变化选择
    function handleRankChange(e) {
        filterByAllConditions();
        currentPage = 1;
        renderTable();
    }

    // 上一页
    function goToPrevPage() {
        if (currentPage > 1) {
            currentPage--;
            renderTable();
            scrollToTableTop();
        }
    }

    // 下一页
    function goToNextPage() {
        const maxPage = Math.ceil(filteredData.length / pageSize);
        if (currentPage < maxPage) {
            currentPage++;
            renderTable();
            scrollToTableTop();
        }
    }

    // 滚动到表格顶部
    function scrollToTableTop() {
        document.querySelector('.overflow-x-auto').scrollIntoView({ behavior: 'smooth' });
    }

    // 格式化数字显示，保留2位小数且不显示千位分隔符
    function formatNumber(number) {
        if (number === null || number === undefined || isNaN(number)) return '0';

        // 处理科学计数法的情况
        let num = typeof number === 'string' && number.includes('E')
            ? new Number(number)
            : Number(number);
        return num.toLocaleString('zh-CN', {
            maximumFractionDigits: 2,
            minimumFractionDigits: 2, // 确保始终显示2位小数
            useGrouping: false // 禁用千位分隔符
        });
    }

    // 为CSV格式化数字
    function formatNumberForCsv(number) {
        if (!number) return '0';
        return new Number(number).toFixed(2);
    }

    // 根据数字正负设置样式类
    function formatNumberClass(number) {
        if (!number) return '';
        const num = new Number(number);
        if (num > 0) return 'text-red-500';
        if (num < 0) return 'text-green-500';
        return '';
    }

    function formatConcept(concept) {
        // 处理空值情况
        if (!concept) return { display: '-', title: '' };

        // 处理长度限制
        if (concept.length > 13) {
            return {
                display: concept.substring(0, 13) + '...',
                title: concept
            };
        }

        // 正常显示
        return {
            display: concept,
            title: ''
        };
    }

    // 计算排名变化
    function calculateRankChange(current, old) {
        // 统一转换为数值类型，无法转换则视为无效值
        const currentRank = Number(current);
        const oldRank = Number(old);

        // 验证参数有效性（必须是有限数字且大于0，排名通常从1开始）
        if (isNaN(currentRank) || isNaN(oldRank) ||
            !isFinite(currentRank) || !isFinite(oldRank) ||
            currentRank <= 0 || oldRank <= 0) {
            return { class: 'text-gray-400', html: '-' };
        }
        const change = oldRank - currentRank;

        if (change < 0) {
            return {
                class: 'text-green-500 font-medium',
                html: `<i class="fa fa-arrow-down" aria-hidden="true"></i> ${Math.abs(change)}`
            };
        } else if (change > 0) {
            return {
                class: 'text-red-500 font-medium',
                html: `<i class="fa fa-arrow-up" aria-hidden="true"></i> ${change}`
            };
        } else {
            // 排名不变
            return {
                class: 'text-gray-500',
                html: `<i class="fa fa-minus" aria-hidden="true"></i> 0`
            };
        }
    }

    // 计算主力成本获利情况
    function getMainProfit(price, mainCost) {
        // 统一转换为数值类型
        const nowPrice = Number(price);
        const costPrice = Number(mainCost);

        // 验证参数有效性
        if (isNaN(nowPrice) || isNaN(costPrice) ||
            !isFinite(nowPrice) || !isFinite(costPrice) ||
            nowPrice <= 0 || costPrice <= 0) {
            return { class: 'text-gray-400', html: '-' };
        }

        // 计算获利金额和百分比
        const profitAmount = nowPrice - costPrice;
        const profitPercent = ((profitAmount / costPrice) * 100).toFixed(2);

        // 根据获利情况返回不同样式和内容
        if (profitAmount > 0) {
            return {
                class: 'text-red-500 font-medium',
                html: `${profitPercent}%`
            };
        } else if (profitAmount < 0) {
            return {
                class: 'text-green-500 font-medium',
                html: `${profitPercent}%`
            };
        } else {
            return {
                class: 'text-gray-500',
                html: `0.00%`
            };
        }
    }


    function getSelectedStockCodesJQ() {
        let selectCode = $('input[name="select-stockCode"]:checked').map(function() {
            return $(this).val();
        }).get().join(',');
        copyToClipboard(selectCode);
    }

    /**
     * 批量打开选中的股票页面（每个股票在新标签页打开）
     */
    function openSelectedStockCodesJQ() {
        // 获取所有选中的股票代码
        let selectedCodes = $('input[name="select-stockCode"]:checked').map(function() {
            return $(this).val();
        }).get();

        // 处理未选中的情况
        if (selectedCodes.length === 0) {
            alert('请先选择股票');
            return;
        }
        // 遍历选中的每个股票代码，单独打开新页面
        selectedCodes.forEach(code => {
            // 为每个代码构建单独的URL（避免参数过长，且符合单股票页面设计）
            const targetUrl = `/stocksflow/summarystock?code=${encodeURIComponent(code)}`;
            // 每个股票在新标签页打开
            window.open(targetUrl, '_blank');
        });
    }

    /**
     * 批量用AI分析分析
     */
    function openViewRisksStockCodesJQ() {
        // 获取所有选中的股票代码
        let selectCode = $('input[name="select-stockCode"]:checked').map(function() {
            return $(this).val();
        }).get().join(',');
        copyToClipboard(selectCode+"这些股票有什么风险?给出详细分析。");
        window.open("https://www.doubao.com/chat/21018538323617794", '_blank');

        // 遍历选中的每个股票代码，单独打开新页面
        // selectedCodes.forEach(code => {
        //     // 为每个代码构建单独的URL（避免参数过长，且符合单股票页面设计）
        //     const targetUrl = `/stocksflow/summarystock?code=${encodeURIComponent(code)}`;
        //     // 每个股票在新标签页打开
        //
        // });
    }


    // 1. 首先修改openSelectedStockCodesJQ函数，支持传入单个代码
    function openSelectedStockCodes(selectedCode) {
        let selectedCodes;

        // 如果有传入单个代码，则直接使用该代码
        if (selectedCode) {
            selectedCodes = [selectedCode];
        } else {
            // 否则获取所有选中的代码（保持原逻辑）
            selectedCodes = $('input[name="select-stockCode"]:checked').map(function() {
                return $(this).val();
            }).get();
        }

        // 处理未选中的情况
        if (selectedCodes.length === 0) {
            alert('请先选择股票');
            return;
        }

        // 拼接股票代码为参数（多个代码用逗号分隔）
        const codeParam = selectedCodes.join(',');

        // 构建基于根目录的相对路径
        const targetUrl = `/stocksflow/summarystock?code=${encodeURIComponent(codeParam)}`;

        // 在新标签页打开目标地址
        window.open(targetUrl, '_blank');
    }

    // 添加复制功能
    function copyToClipboard(stockCodes) {
        // 阻止事件冒泡，避免触发父元素的点击事件
        event.stopPropagation();

        if (!stockCodes || stockCodes.trim() === '') {
            alert('没有股票代码可复制');
            return;
        }

        // 使用现代浏览器的剪贴板API
        if (navigator.clipboard && window.isSecureContext) {
            navigator.clipboard.writeText(stockCodes).then(() => {
                // 显示成功提示
                showCopySuccessToast(stockCodes.split(',').length);
            }).catch(err => {
                console.error('复制失败:', err);
                fallbackCopy(stockCodes);
            });
        } else {
            // 降级方案
            fallbackCopy(stockCodes);
        }
    }

    // 降级复制方案
    function fallbackCopy(text) {
        const textArea = document.createElement('textarea');
        textArea.value = text;
        textArea.style.position = 'fixed';
        textArea.style.left = '-999999px';
        textArea.style.top = '-999999px';
        document.body.appendChild(textArea);
        textArea.focus();
        textArea.select();

        try {
            document.execCommand('copy');
            showCopySuccessToast(text.split(',').length);
        } catch (err) {
            console.error('降级复制也失败了:', err);
            alert('复制失败，请手动复制：' + text);
        } finally {
            document.body.removeChild(textArea);
        }
    }

    // 显示复制成功的提示
    function showCopySuccessToast(count) {
        // 创建提示元素
        const toast = document.createElement('div');
        toast.style.cssText = `
                position: fixed;
                top: 20px;
                right: 20px;
                background: #28a745;
                color: white;
                padding: 12px 20px;
                border-radius: 6px;
                box-shadow: 0 4px 12px rgba(0,0,0,0.3);
                z-index: 9999;
                font-size: 12px;
                font-weight: 500;
                display: flex;
                align-items: center;
                gap: 8px;
                opacity: 0;
                transform: translateX(100%);
                transition: all 0.3s ease;
            `;

        toast.innerHTML = `
                <i class="fa fa-check-circle" aria-hidden="true"></i>
                已复制 ${count} 个股票代码
            `;

        document.body.appendChild(toast);

        // 动画显示
        setTimeout(() => {
            toast.style.opacity = '1';
            toast.style.transform = 'translateX(0)';
        }, 100);

        // 3秒后自动隐藏
        setTimeout(() => {
            toast.style.opacity = '0';
            toast.style.transform = 'translateX(100%)';
            setTimeout(() => {
                if (document.body.contains(toast)) {
                    document.body.removeChild(toast);
                }
            }, 300);
        }, 3000);
    }
</script>
</body>
</html>
